<?php
/**
 * XmuSlh, web platform of Student Association Federation of Xiamen University
 * 
 * Rewritting one or some pages of StatusNet. 
 * To get the original version, please visit <http://status.net/>.
 * 
 * StatusNet, the distributed open-source microblogging tool
 * 
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * An action that is a invisiable json action, meaning that it
 * returns json data whatever.
 * 
 * It uses to handle the ajax cropping poster from the client.
 * 
 * 用于接收并且处理Poster的剪裁和添加的Action.
 * 
 * @author		ytukie <ytukie@gmail.com>
 * @version		0.1
 */

// XmuSlh only.
if ( !defined('XMUSLH')) { exit(1); }

// Requirements.
require_once INSTALLDIR . '/lib/slh_jsonaction.php';
require_once INSTALLDIR . '/lib/slh_util.php';

require_once INSTALLDIR . '/classes/Poster.php';

class CropposterjsonAction extends JsonAction
{
	/**
	 * The returning data items.
	 */
	var $status = '0';			// 0 error, 1 success
	var $error = '';			// set if status = 0
	var $poster_id = '0';		// id of the poster
	var $thumbnailurl = '';		// url of the uploaded thumbnail poster
	
	/**
	 * The uploaded poster_id. Delete it!
	 */
	var $uploadedposter_id;
	
	/**
	 * The name of the uploaded file which is being cropped.
	 */ 
	var $uploadedoriginalname;
	
	/**
	 * x, y, w, h
	 */
	var $poster_crop_x;
	var $poster_crop_y;
	var $poster_crop_w;
	var $poster_crop_h;
	
	/**
	 * Size type.
	 */
	var $sizetype;
	
	/**
	 * Some initializations. Might block this request.
	 */
	function prepare($args)
	{
		parent::prepare($args);

// TODO: Check the user and the rights.

		// Inits the jsondata.
		$this->jsondata['status'] = $this->status;
		$this->status =& $this->jsondata['status'];
		$this->jsondata['error'] = $this->error;
		$this->error =& $this->jsondata['error'];
		$this->jsondata['poster_id'] = $this->poster_id;
		$this->poster_id =& $this->jsondata['poster_id'];
		$this->jsondata['thumbnailurl'] = $this->thumbnailurl;
		$this->thumbnailurl =& $this->jsondata['thumbnailurl'];
		
		// Get the uploaded poster_id if uploaded before. Not 0.
		// Not so strict that some minded people mind change it.
		$this->uploadedposter_id = $this->getTrimmedArg('puploadedposter_id');
		
		// The name of the uploaded file which is being cropped.
		$this->uploadedoriginalname = $this->getTrimmedArg('puploadedoriginalname');
		// x, y, w, h
		$this->poster_crop_x = $this->getTrimmedArg('pposter_crop_x');
		$this->poster_crop_y = $this->getTrimmedArg('pposter_crop_y');
		$this->poster_crop_w = $this->getTrimmedArg('pposter_crop_w');
		$this->poster_crop_h = $this->getTrimmedArg('pposter_crop_h');
		// size type
		$this->sizetype = $this->getTrimmedArg('psizetype');

		return true;
	}
	
	/**
	 * Handle a request.
	 */
	function handle($args)
	{
		parent::handle($args);
		
		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			$this->handlePost();
		} else {
			// slh_redirectto_default();
		}
		
		parent::showJson();
	}
	
	/**
	 * Handle a post, if a really poster uploading post.
	 */
	function handlePost()
	{
		try {
//TODO: the id		
			$news_id = 0;
			
			// The original image file xxxx-temp-xxxx.xxx
			$uploadedoriginalpath = Poster::path($this->uploadedoriginalname);
			$originalfile = new ImageFile($news_id,
										  $uploadedoriginalpath,
										  $this->uploadedoriginalname);
										
			// Firstly, to resize to the cropped one.
			$postername = Poster::tempname2Postername($this->uploadedoriginalname);
			$posterpath = Poster::path($postername);
/*
var_dump($this->poster_crop_w);
var_dump($this->poster_crop_h);
var_dump($this->poster_crop_x);
var_dump($this->poster_crop_y);
*/

			// originalfile(x, y, w, h) => posterfile(0, 0, w, h);
			$originalfile->posterResize($posterpath,
									    $this->poster_crop_w,				// posterfile.w
									    $this->poster_crop_h,				// posterfile.h
									    $this->poster_crop_x,				// originalfile.x
									    $this->poster_crop_y,				// originalfile.y
									    $this->poster_crop_w,				// originalfile.w
									    $this->poster_crop_h);				// originalfile.h
										
			// Then, to resize to the thumbnail one.
			// originalfile(x, y, w, h) => thumbnail(0, 0, $this->sizetype, POSTER_MAX_HIGHT)
			$thumbnailname = Poster::filename2Thumbnailname($postername);
			$thumbnailpath = Poster::path($thumbnailname);
			$originalfile->posterResize($thumbnailpath,
									    $this->sizetype,					// posterfile.w
									    POSTER_MAX_HIGHT,					// posterfile.h
									    $this->poster_crop_x,				// originalfile.x
									    $this->poster_crop_y,				// originalfile.y
									    $this->poster_crop_w,				// originalfile.w
									    $this->poster_crop_h);				// originalfile.h
									  	
			// Clean the original file up.
			$originalfile = null;
			@unlink($uploadedoriginalpath);
			
			// Adds into the database.
			$poster_id = Poster::add(array('news_id' => $news_id,
										   'postername' => $postername,
										   'size' => $this->sizetype));
			
			if ( !$poster_id) {
				// Try to delete the uploaded file.
				@unlink($posterpath);
				@unlink($thumbnailpath);
				@unlink($uploadedoriginalpath);
					
				throw new Exception('添加' . $posterfile->name . '失败, 请重新尝试添加.');
			}
			
			// While a new poster is uploaded successfully, then check the old one!
			// See the uploadedposter_id is existed already, then clear it up!
			// Poster::removeIfAiredPoster($this->uploadedposter_id);
			
			// Success. Set the json datas.
			$this->status = '1';
			$this->poster_id = $poster_id;
			
			// Random for url to avoid the caching mechanism.
			$this->thumbnailurl = sprintf('%s?r=%s', Poster::url($thumbnailname), slh_mtrand(2));
			// $this->thumbnailurl = sprintf('%s?r=%s', Poster::url($postername), slh_mtrand(2));
			
		} catch (Exception $e) {
			$this->error = $e->getMessage();
			return;
		}
	}
}

?>